<?php

namespace Buu\Modules\Constant\Controllers;

use App\Admin\Extensions\Tools\UserButton;
use App\Models\ConstantType;
use App\Models\ConstantValue;
use App\Models\ConstantValueGroup;
use App\Models\ConstantValueGroupRelation;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Show;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;


use Encore\Admin\Facades\Admin;
use App\Http\Controllers\Controller;
use Encore\Admin\Widgets\Box;

class ConstantTypeController extends Controller
{
    private $id;

    /**
     * title
     * @return string
     */
    protected function title()
    {
        return "常量类型列表";
    }

    const TYPE_INT = 1;
    const TYPE_SRTRING =2 ;

    const VALUE_TYPE_LABEL = [
        self::TYPE_INT  => '整型',
        self::TYPE_SRTRING => '字符串',

    ];

    public function index(Request $request, Content $content)
    {
        return $content
            ->header($this->title())
            ->body($this->grid());
    }

    /**
     * 列表构建
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new ConstantType());
        $grid->model()->orderBy('id');
        $grid->disableFilter();
        $grid->disableExport();
        $grid->disableBatchActions();
        $grid->disableCreateButton();

        $grid->column('interface_name', '常量类型接口名');
        $grid->column('name', '常量类型名称');
        $grid->column('desc', '常量类型描述')->editable();
        $grid->column('value_type', '常量值类型')->using(['1' => '整型', '2' => '字符串'])->label();
        $grid->column('is_gumper', '是否使用发号器')->using(['1' => '使用', '0' => '不使用'])->label();
        $grid->column('查看')->display(function() {
            return "<a href='/admin/Constant/constant-type/detail/$this->id'> 查看</a>";
        })->width(100);

        $grid->column('常量值')->display(function() {
            return "<a href='/admin/Constant/constant-value/list/$this->id'> 配置常量值</a>";
        })->width(100);


        $grid->column('常量组')->display(function() {
            return "<a href='/admin/Constant/constant-value-group/list/$this->id'> 配置常量组</a>";
        })->width(100);

        $grid->tools(function (Grid\Tools $tool) {
            $tool->append(new UserButton(UserButton::TYPE_HREF, '', '新增常量 类型', 'fa-plus-circle', url('/admin/Constant/constant-type/add/')));
            $tool->append(new UserButton(UserButton::TYPE_HREF, '', '去发布', 'fa-cloud-upload', url('/admin/Constant/constant-version')));
        });


        // 全部关闭
        $grid->disableActions();
        return $grid;
    }

    public function detail($iCTypeid)
    {
        return Admin::content(function (Content $content) use ($iCTypeid) {

            $aCType = ConstantType::getOne($iCTypeid);
            $content->header($aCType['name'].' ( '.$aCType['interface_name'].' ) - 常量类型详情');

            $aCValue = ConstantValue::select('name','value','desc',)->where('constant_type_id',$iCTypeid)->orderBy('id')->get()->toArray();
            $table1 = new Table(['类型','值','描述'], $aCValue);
            $box1 = new Box($aCType['interface_name'].'定义 常量值', $table1);
            $content->row($box1->solid()->style('primary'));

            $aCGroup = ConstantValueGroup::query()->where('constant_type_id',$iCTypeid)->orderBy('id')->get()->toArray();
            foreach ($aCGroup as $aCGroupValue){
                $aCGroupRelationIds = ConstantValueGroupRelation::where('constant_type_id',$iCTypeid)->where('status',1)->where('constant_value_group_id',$aCGroupValue['id'])->pluck('constant_value_id')->toArray();

                $aCGroupRelation = ConstantValue::whereIn('id',$aCGroupRelationIds)->select('name','value','desc')->get()->toArray();

                $table = new Table(['常量名称','常量值','常量描述'], $aCGroupRelation);
                $box = new Box($aCGroupValue['name'].'( '.$aCGroupValue['value'].' ) - 常量组', $table);
                $content->row($box->solid()->style('default'));
            }

        })
            ->breadcrumb(
            ['text' => '常量列表', 'url' => '/Constant/constant-type/list'],
            ['text' => '详情']
        );
    }

    public function listsave(Request $request)
    {
        $request = $request->all();
        $rs = [];
        if(!empty($request['value'])){
            $updateData = array(
                "desc" =>$request['value']
            );
            $rs = ConstantType::saveInfo($request['pk'],$updateData);
        }

        if($rs){
            return response()->json(['status'=>true,'message'=>'修改成功']);

        }else {
            return response()->json(['status' => false, 'message' => '修改失败']);
        }
    }


    public function add(Request $request, Content $content)
    {
        $request = $request->all();
        return $content
            ->header('信息完善')

            ->breadcrumb(
                ['text' => '常量列表', 'url' => '/Constant/constant-type/list'],
                ['text' => '信息完善']
            )
            ->body(self::addAction($request));
    }

    public function addAction($request)
    {
        $form = new Form(new ConstantType());
        $form->html("<span style='color:red;'>不可以修改, 请仔细填写</span>");
        $form->text('interface_name', '常量类型接口名')->pattern('[a-zA-Z]+')->width('300px')->rules('required')->help('英文，例如:userType ;不可重复');
        $form->text('name', '常量类型名称')->rules('required')->pattern('[\u4e00-\u9fa5]+')->width('300px')->help('中文；不可重复');
        $form->text('desc', '常量类型描述')->width('300px')->rules('required');
        $form->radio('value_type', '常量值类型')->rules('required')
            ->options([
                1 => '整型',
                2 => '字符串',
            ])->when(1, function (Form $form) {

                $form->radio('is_gumper', '是否使用发号器')
                    ->options([
                        1 => '使用',
                        0 => '不使用',
                    ])->when(1, function (Form $form) {

                        $form->text('gumper', '当前发号器最大值')->rules('regex:/^\d+$/', [
                            'regex' => 'code必须全部为数字',
                        ])->default(0);
                    });
            });

        $form->saving(function (Form $form) {

            //interface_name和name 唯一
            $form->interface_name =  trim($form->interface_name);
            $form->name =  trim($form->name);

            $aMsg = [];

            if(!empty(ConstantType::getFromInterName($form->interface_name))){
                $aMsg = ['title' =>'常量类型接口名 重复'];
            }
            if(!empty(ConstantType::getFromName($form->name))){
                $aMsg = ['title' =>'常量类型名称 重复'];
            }
            if(!empty($aMsg)){
                $error = new MessageBag($aMsg);
                return back()->with(compact('error'))->withInput();
            }
        });
        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
        });

        $form->tools(function (Form\Tools $tools) {
            // 去掉`列表`按钮
            $tools->disableList();

            // 去掉`删除`按钮
            $tools->disableDelete();

            // 去掉`查看`按钮
            $tools->disableView();
        });

        $form->footer(function ($footer) {
            // 去掉`查看`checkbox
            $footer->disableViewCheck();

            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();

            // 去掉`继续创建`checkbox
            $footer->disableCreatingCheck();

        });
        $form->setAction('/admin/Constant/constant-type/addsave');
        return $form;
    }


    public function addsave(Request $request)
    {
        $request = $request->all();
        if(!empty(ConstantType::getFromInterName($request['interface_name']))){
            $sMsg = '常量类型接口名 重复';
        }
        if(!empty(ConstantType::getFromName($request['name']))){
            $sMsg = '常量类型名称 重复';
        }
        if(!empty($sMsg)){
            admin_toastr($sMsg, 'error', ['timeOut' => 5000]);
            return redirect('/admin/Constant/constant-type/add')->withInput();
        }

        $aValue = [
            'interface_name'   => $request['interface_name'],
            'name'             => $request['name'],
            'desc'             => $request['desc'],
            'value_type'       => $request['value_type'],
            'gumper'           => $request['gumper']??0,
            'is_gumper'        => $request['is_gumper']??0,
        ];
        if( ConstantType::insert($aValue)){
            $sMsg = 'success';
        }else{
            $sMsg = 'error';
        }

        admin_toastr($sMsg, $sMsg, ['timeOut' => 3]);
        return redirect('/admin/Constant/constant-type/list');
    }

}